<template>
  <a-modal
    :maskClosable="false"
    :title="`${ okHidden ? '' : model && model.customer_id ? '编辑' : '新增'}志愿者`"
    :ok-button-props="{ style: okHidden && { display: 'none' } }"
    :width="680"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleOK"
    @cancel="() => { (checkedData = {}, checked = false), $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item
          label="手机号"
          :class="checked && !checkedData.customer_id && 'extra'"
          :extra="!checked ? '请输入您要添加志愿者的手机号' : !checkedData.customer_id ? '检测不到当前手机号，请该志愿者下载注册飞村app注册账号' : ''"
        >
          <a-row :gutter="8">
            <a-col :span="12">
              <a-input
                type="text"
                :maxLength="11"
                :disabled="!!model"
                @change="phoneChange"
                v-decorator="[
                  'mobile',
                  { rules: [{ validator: this.checkPhone }] }
                ]"
              />
            </a-col>
            <a-col :span="12">
              <a-button @click="verify" :loading="verifyParams.loading" v-if="!model">验证</a-button>
            </a-col>
          </a-row>
        </a-form-item>
        <template v-if="checkedData.customer_id">
          <a-form-item v-show="false">
            <a-input v-decorator="['customer_id', { initialValue: checkedData.customer_id }]" disabled />
          </a-form-item>
          <a-form-item label="志愿者名称">
            <a-input disabled placeholder="请输入志愿者名称" :maxLength="10"  v-decorator="['nickname', {rules: [{required: true, message: '志愿者名称不能为空！' }, {max: 10, message: '最大可输入10个字符！' }]}]" />
          </a-form-item>
          <a-form-item label="志愿者姓名">
            <a-input :style="{ marginLeft: okHidden ? '3px' : '10px' }" :disabled="okHidden" placeholder="请输入志愿者姓名" :maxLength="10"  v-decorator="['fullname', {rules: [{required: true, message: '志愿者姓名不能为空！'}, {max: 10, message: '最大可输入10个字符！' }]}]" />
          </a-form-item>
          <a-form-item label="家庭">
            <village-tree-selector :style="{ marginLeft: okHidden ? '6px' : '10px' }" :disabled="okHidden" v-decorator="['village_ids', { initialValue: [], rules: [{ required: true, message: '请至少选择一个家庭所属村！' }]}]"></village-tree-selector>
          </a-form-item>
        </template>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { checkMobile } from '@/api'
import VillageTreeSelector from '@/components/VillageTreeSelector'

// 表单字段
const fields = ['nickname', 'fullname', 'village_ids', 'mobile', 'customer_id']
const phoneRegex = new RegExp(/^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0,1,3,6-8])|(18[0-9])|(19[8,9])|(166))[0-9]{8}$/)

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    okHidden: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    serveList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    return {
      form: this.$form.createForm(this),
      currentLength: 0,
      realShow: false,
      verifyParams: {
        loading: false,
        disabled: false
      },
      checkedData: {},
      checked: false
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
        if (this.model) {
          this.checked = true
          this.checkedData = this.model
          this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model, fields))
          })
        }
    })
  },
  methods: {
    textareaChange () {
      this.form.validateFields((errors, values) => {
        this.currentLength = values.content.length
      })
    },
    phoneChange (e) {
      if (this.checked) {
        this.checkedData = {}
        this.checked = false
      }
    },
    // 检查手机号
    checkPhone (rule, value, callback) {
      if (!phoneRegex.test(value)) {
        callback(new Error('电话号码输入格式有误'))
      }
      callback()
    },
    async verify () {
      const mobile = this.form.getFieldsValue().mobile
      if (!phoneRegex.test(mobile)) { return }
      this.verifyParams.loading = true
      try {
        const res = await checkMobile({ mobile }) || {}
        this.verifyParams.loading = false
        this.checked = true
        this.checkedData = res
        this.$nextTick(() => {
          this.form.setFieldsValue(res)
        })
      } catch (err) {
        this.verifyParams.loading = false
      }
    },
    handleOK () {
      if (!this.checked) return this.$message.error('请先验证手机号码')
      if (!this.checkedData.customer_id) { return }
      this.$emit('ok')
    }
  },
  components: {
    VillageTreeSelector
  }
}
</script>

<style scoped lang="less">
  .extra{
    /deep/ .ant-form-extra{
      color: #f00
    }
  }
</style>
